package com.slz3.business.module.memberManagement.memCollect.service;

import com.slz3.business.frame.enums.ValidFlag;
import com.slz3.business.frame.module.Repositorys;
import com.slz3.business.frame.module.Services;
import com.slz3.business.frame.redis.Jedis;
import com.slz3.business.frame.steward.PageableSteward;
import com.slz3.business.frame.redis.RK;
import com.slz3.business.frame.util.VE;
import com.slz3.business.module.memberManagement.memCollect.domain.MemCollect;
import com.slz3.business.module.memberManagement.memCollect.domain.MemCollectFactory;
import com.slz3.business.module.memberManagement.memCollect.steward.MemCollectSpecification;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.*;

@Slf4j
@Service
public class MemCollectServiceImpl implements MemCollectService {

    @Override
    public MemCollect save(MemCollect memCollect) {
        MemCollect memCollectDB = Repositorys.memCollect.save(MemCollectFactory.initBaseFields(memCollect));
        if(VE.isNotEmpty(Jedis.db0.get(RK.USER_COLLECTION.concat(":").concat(memCollectDB.getUuid().toString())))){
            Jedis.db0.remove(RK.USER_COLLECTION.concat(":").concat(memCollectDB.getUuid().toString()));
        }
        Jedis.db0.set(RK.USER_COLLECTION.concat(":").concat(memCollectDB.getUuid().toString()),memCollectDB);
        return memCollectDB;
    }

    @Override
    public Page<MemCollect> page(MultiValueMap<String, String> params) {
        Page<MemCollect> memCollectPage = Repositorys.memCollect.findAll(
                MemCollectSpecification.findJoin(params), PageableSteward.extract(params)
        );
        return memCollectPage;
    }

    @Override
    public MemCollect modify(MemCollect memCollectNew) {
        return Repositorys.memCollect.saveAndFlush(MemCollectFactory.initBaseFields(memCollectNew));
    }

    @Override
    public Optional<MemCollect> single(UUID uuid) {
        Optional<MemCollect> memCollect = Jedis.db0.get(RK.USER_COLLECTION.concat(":").concat(uuid.toString()));
        if (VE.isEmpty(memCollect)){
            memCollect =Repositorys.memCollect.findById(uuid);
        }
        return memCollect;
    }

    @Override
    public List<MemCollect> findAllByUuids(Iterable<UUID> uuids) {
        return Repositorys.memCollect.findAllById(uuids);
    }

    @Override
    public List<MemCollect> delete(List<MemCollect> memCollectList) {
        memCollectList.stream().forEach(item -> {
            item.setValidFlag(ValidFlag.DEL);
            MemCollectFactory.initBaseFields(item);
            Jedis.db0.remove(RK.USER_COLLECTION.concat(":").concat(item.getUuid().toString()));
        });
        return Services.memCollectTransactional.batchModify(memCollectList);
    }

}
